/**
 * Created by leon on 2017/6/20.
 */


import {Injectable} from '@angular/core';
import {
    ActivatedRouteSnapshot, CanActivate, CanActivateChild, CanLoad, Route, Router,
    RouterStateSnapshot
} from '@angular/router';
import {DataService} from '../data.service';

@Injectable()
export class XAuthGuard implements CanActivate, CanActivateChild, CanLoad {
    constructor (
        private router: Router,
        private dataService: DataService
    ) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        const url = state.url;

        return this.checkXAuth(url);
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return this.canActivate(route, state);
    }

    canLoad(route: Route): Promise<boolean> {
        // console.log('canload');
        const url = `/${route.path}`;

        return this.checkXAuth(url);
    }

    checkXAuth(url: string): Promise<boolean> {
        return this.dataService.getXAuth().then(() => {
            if (this.dataService.xAuth) {
                return true;
            } else {
                // this.router.navigate(['/']);
                return false;
            }
        });
    }
}